package com.liaoyifan.core.config;

import com.liaoyifan.core.constant.Constants;
import com.liaoyifan.core.constant.Properties;
import com.liaoyifan.core.datasource.DynamicDataSource;
import com.liaoyifan.core.properties.DataSourceProperties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionTemplate;

@SuppressWarnings("unused")
@EnableTransactionManagement
@Configuration
@ConditionalOnProperty(name = Properties.DATASOURCE_ENABLE, havingValue = Constants.TRUE)
public class DataSourceConfiguration {

    @Bean("dataSourceProperties")
    @ConfigurationProperties(prefix = Properties.LIAOYIFAN + Properties.DATASOURCE)
    public DataSourceProperties DataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean("dataSource")
    @Primary
    public DataSource dataSource(
            @Qualifier("dataSourceProperties") DataSourceProperties dataSourceProperties) {
        return new DynamicDataSource(dataSourceProperties);
    }

    @Bean("transactionManager")
    @Primary
    public PlatformTransactionManager transactionManager(
            @Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean("transactionTemplate")
    @Primary
    public TransactionTemplate transactionTemplate(
            @Qualifier("transactionManager") PlatformTransactionManager transactionManager) {
        return new TransactionTemplate(transactionManager);
    }
}
